package com.tom;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import static com.tom.Contants.*;

/**
 * @author yanghongjun19
 * @date 2021/01/06
 **/
public class RpcRegister {

    private String zookeeperCon;

    private ZooKeeper zooKeeper;

    /**
     * 需要传入zookeeper链接 比如: localhost:2181,localhost:2182,localhost:2183
     *
     * @param zookeeperCon
     */
    public RpcRegister(String zookeeperCon) {
        this.zookeeperCon = zookeeperCon;
    }

    /**
     * 创建节点
     *
     * @param data 节点内容
     * @throws Exception 异常
     */
    public void createNode(String data) throws Exception {
        zooKeeper = new ZooKeeper(zookeeperCon, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
        if (zooKeeper != null) {
            try {
                Stat stat = zooKeeper.exists(REGISTRY_PATH, false);
                if (stat == null) {
                    zooKeeper.create(REGISTRY_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                zooKeeper.create(DATA_PATH, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("zookeeper异常" + e.getMessage());
            }
        }

    }
}
